const uac = require("../config/ua.json"), loger = require("./loger");
let uaIndex = 0, win = null, loadedFun = null, ldt = 0, st = 0;

// chrome.webRequest.onBeforeSendHeaders.addListener(function(details) {
	// for (var i = 0; i < details.requestHeaders.length; ++i) {
		// if (details.requestHeaders[i].name === 'User-Agent') {
			// details.requestHeaders[i].value = uac[uaIndex];
			// break;
		// }
	// }
	// return {requestHeaders: details.requestHeaders};
// },{urls: ["<all_urls>"]}, ["blocking", "requestHeaders"]);


module.exports.openUrl = (url, rfun)=>{
	nw.App.clearCache();
	//nw.App.closeAllWindows();
	//const fs = require('fs');
	//fs.rmdirSync(nw.App.dataPath);
	//if(win){
	//	nw.App.closeAllWindows();
	//	win = null;
	//}
	if(!url) {
		//nw.Window.open(url);
		return;
	}
	loadedFun = rfun;
	loger.info("open ", url);
	if(win){
		win.window.location.href = url;
		return;
	}
	nw.Window.open(url, {width:960,height:800}, function(w){
		win = w;//loger.info("open win ", url);
		w.on('loaded', function() {//loger.info("open loaded ", url);
			//w.window.console.log(w.window.location.href);
			// win.cookies.getAll({}, (ck)=>{
				// for(let i=0;i<ck.length;i++){
					// loger.info("loaded cookie", JSON.stringify(ck[i]));
				// }
			// });
			if((new Date().getTime() - ldt) < 3000) return;
			ldt = new Date().getTime();
			if("end" in global.sdObj){
				loadedFun = null;
				return;
			} 
			if(loadedFun) {
				if(loadedFun(w)) loadedFun = null;
			}
		});
	});
	// if(win){
		// win.removeAllListeners();
		// win.close(true);
	// } 
	// win = null;	
}

module.exports.getImg = (tp, tm, rfun)=>{ //tp 暂时只支持tmp 和 err
	if(win){
		setTimeout(()=>{
			win.capturePage((buf)=>{
				const fs = require("fs");
				fs.writeFileSync(tp+".png", buf);
				global.sdObj[tp] = 1;
				if(rfun) rfun();
			}, {format:'png',datatype:'buffer'});
		},tm);
	}
}

module.exports.setUserAgent = (i)=>{
	if(i >= 0 && i < uac.length) uaIndex = i;
}

module.exports.run = (rfun, ldfun)=>{
	if(ldfun) loadedFun = ldfun;
	rfun(win);
}

module.exports.exeload = ()=>{
	if(win && loadedFun && (new Date().getTime() - ldt) > 8000){
		loger.info("enter loaded");
		if(loadedFun(win)) loadedFun = null;
	}
}

module.exports.clload = ()=>{
	loadedFun = null;
}

module.exports.reload = ()=>{
	if(win && (new Date().getTime() - ldt) > 8000){
		win.window.location.href = win.window.location.href;
	}
}

//清理cookie
module.exports.rmcookie = ()=>{
	if(win && win.cookies){
		win.cookies.getAll({}, (ck)=>{
			for(let i=0;i<ck.length;i++){
				win.cookies.remove({url:"http"+(ck[i].secure?"s":"")+"://"+ck[i].domain+ck[i].path,name:ck[i].name,storeId:ck[i].storeId});
			}
			loger.info("remove cookie");
		});
	}
}

//打印cookie信息
module.exports.printcookie = ()=>{
	if(win && win.cookies){
		win.cookies.getAll({}, (ck)=>{
			loger.info(JSON.stringify(ck));
		});
	}
}


